package ipebg.mzk.provider.system.service.impl;

import ipebg.mzk.common.util.Page;
import ipebg.mzk.facade.entity.MsAdminFunction;
import ipebg.mzk.facade.entity.MsAdminRoleAuthority;
import ipebg.mzk.facade.entity.MsFunctionOption;
import ipebg.mzk.facade.system.bean.FunctionBean;
import ipebg.mzk.facade.system.bean.FunctionTreeBean;
import ipebg.mzk.facade.system.service.FunctionService;
import ipebg.mzk.facade.system.service.PagerService;
import ipebg.mzk.facade.system.service.RoleService;
import ipebg.mzk.provider.system.dao.AdminRoleAuthorityDao;
import ipebg.mzk.provider.system.dao.FunctionDao;
import ipebg.mzk.provider.system.dao.MsFunctionOptionDao;
import ipebg.mzk.provider.system.dao.MsFunctionRoleOptionDao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("functionServiceImpl")
public class FunctionServiceImpl implements FunctionService {
	private static Log log = LogFactory.getLog(FunctionServiceImpl.class);
	@Resource(name="functionDao")
	FunctionDao functionDao;
	
	@SuppressWarnings("rawtypes")
	@Resource(name = "pageServiceImpl")
	private PagerService  pageServiceImpls;
	
	@Resource(name="adminRoleAuthorityDao")
	AdminRoleAuthorityDao adminRoleAuthorityDao;
	
	@Resource(name="msFunctionOptionDao")
	MsFunctionOptionDao functionOptionDao;
	
	@Resource(name="msFunctionRoleOptionDao")
	MsFunctionRoleOptionDao msFunctionRoleOptionDao;
	
	@Resource(name="roleServiceImpl")
	RoleService roleService;

	@Override
	@Transactional
	public Page getFunctionList(MsAdminFunction function, int from, int length) throws Exception {
		Page functionList;
		String hql = "from MsAdminFunction u where u.functionId is not null";
		if(function != null){
			if(function.getFunctionName() !=null && !function.getFunctionName().equals("")){
				hql += " and u.functionName like '%"+function.getFunctionName()+"%'";
			}
			if(function.getFunctionCode() !=null && !function.getFunctionCode().equals("")){
				hql += " and u.functionCode like '%"+function.getFunctionCode()+"%'";
			}		
		}			
		hql+=" order by u.functionCode asc";
		
		try {
			functionList = pageServiceImpls.findPageByhqlQuery(from, length, hql);
		} catch (Exception e) {
			throw e;
		}
		return functionList;
	}

	@Override
	@Transactional
	public void saveOrUpdate(MsAdminFunction function) {
		try {
			functionDao.saveOrUpdate(function);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	@Transactional
	public boolean deleteFunction(String functionId) throws Exception {
		boolean flag = false;
		try {
			MsAdminFunction function = functionDao.findById(functionId);
			functionDao.delete(function);
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return flag;
	}

	@Override
	@Transactional
	public MsAdminFunction findMsAdminFunctionById(String functionId) {
		MsAdminFunction function = functionDao.findById(functionId);
		return function;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public MsAdminFunction findMsAdminFunctionByCode(String functionCode) {
		List<MsAdminFunction> functionList = functionDao.findByProperty(MsAdminFunction.class,new String[]{"functionCode"},new Object[]{functionCode});
		if(functionList.size() > 0)
			return functionList.get(0);
		else
			return null;
	}

	@Override
	@Transactional
	public List<FunctionBean> toBean(List<MsAdminFunction> functionList) throws Exception {
		List<FunctionBean> beanList = new ArrayList<FunctionBean>();
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try{
			for(MsAdminFunction f : functionList){
				FunctionBean bean = new FunctionBean();
				bean.setFunctionId(f.getFunctionId());
				bean.setFunctionName(f.getFunctionName());
				bean.setFunctionCode(f.getFunctionCode());
				bean.setFunctionUrl(f.getFunctionUrl());
				bean.setParentId(f.getParentId());
				
				MsAdminFunction parent = functionDao.findById(f.getParentId());
				String parentName = "";
				if(parent != null)
					parentName = parent.getFunctionName() + " -- " + parent.getFunctionCode();
				bean.setParentName(parentName);
				
				bean.setDescription(f.getDescription());
				
				String createdTime = null;
				if(f.getCreatedTime() == null){
					createdTime = null;
				}else{
					createdTime = date.format(f.getCreatedTime());
				}			
				bean.setCreatedTime(createdTime);
				
				String modifyTime = null;
				if(f.getEditTime() == null){
					modifyTime = null;
				}else{
					modifyTime = date.format(f.getEditTime());
				}
				bean.setEditTime(modifyTime);
				
				beanList.add(bean);
			}
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}
		return beanList;
	}

	@SuppressWarnings("rawtypes")
	@Override
	@Transactional
	public List<FunctionTreeBean> getFunctionTreeList(String parentId) {
		List<FunctionTreeBean> list = null;
		String select = "select f.functionId,f.functionName,f.functionCode from MsAdminFunction f where f.parentId = ? order by f.functionCode asc";
		List oList = functionDao.queryForList(select,new String[]{parentId});
		if(oList!=null) {
			list = new ArrayList<FunctionTreeBean>();
			for(Object o:oList) {
				FunctionTreeBean bean = new FunctionTreeBean();
				Object[] oo = (Object[])o;
				bean.setId((String)oo[0]);
				String text = (String)oo[1] + " -- " + (String)oo[2];
				bean.setText(text);
				bean.setChecked(false);
				List<FunctionTreeBean> children = getFunctionTreeList((String)oo[0]);
				bean.setChildren(children);
				list.add(bean);
			}
		}
		return list;
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	@Transactional
	public List<FunctionTreeBean> getFunctionTreeListByRoleId(String roleId, String parentId) {
		List<FunctionTreeBean> list = null;
		String select = "select f.functionId,f.functionName,f.functionCode from MsAdminFunction f where f.parentId = ? order by f.functionCode asc";
		List oList = functionDao.queryForList(select,new String[]{parentId});
		
		//獲取該角色下具有的菜單Id
		try {
			List<MsAdminRoleAuthority> roleAuthrityList = roleService.findAuthorityByRoleId(roleId);
			List<String> array = new ArrayList<String>();
			for(MsAdminRoleAuthority roleAuth : roleAuthrityList){
				array.add(roleAuth.getFunctionId());
			}
			if(oList!=null) {
				list = new ArrayList<FunctionTreeBean>();
				for(Object o:oList) {
					FunctionTreeBean bean = new FunctionTreeBean();
					Object[] oo = (Object[])o;
					bean.setId((String)oo[0]);
					String text = (String)oo[1] + " -- " + (String)oo[2];
					bean.setText(text);
					
					if(array.contains((String)oo[0])){
						bean.setChecked(true);
					}else
						bean.setChecked(false);
					
					List<FunctionTreeBean> children = getFunctionTreeListByRoleId(roleId,(String)oo[0]);
					bean.setChildren(children);
					list.add(bean);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public List<MsAdminFunction> getAllList() {
		String[] orderStrings = {"functionCode asc"}; 
		return functionDao.findAll(orderStrings);
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public List<MsAdminRoleAuthority> findAuthorityByFunctionId(String functionId) throws Exception {
		List<MsAdminRoleAuthority> resultList = null;
		String hql="from MsAdminRoleAuthority ra where ra.functionId = '"+functionId+"'";		
		try {
			resultList = adminRoleAuthorityDao.queryForList(hql, null);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return resultList;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public List<MsFunctionOption> findOptionByFunctionId(String functionId) throws Exception {
		List<MsFunctionOption> resultList = null;
		String hql="from MsFunctionOption fo where fo.functionId = '"+functionId+"'";		
		try {
			resultList = adminRoleAuthorityDao.queryForList(hql, null);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return resultList;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public void updateRoleFunctionByDBRoleFunction(List<MsAdminRoleAuthority> roleAuthorityList, String[] functionIds, String roleId) throws Exception {
		try{
			//DELETE ALL OLD DATA
			adminRoleAuthorityDao.batchDelete(roleAuthorityList);
			log.info("Delete role list ok ,role authority size is "+roleAuthorityList.size());
			//INSERT NEW DATA
			List<MsAdminRoleAuthority> listRoleAuthority=new ArrayList<MsAdminRoleAuthority>();
			for(String functionId:functionIds){
				if(!functionId.equalsIgnoreCase("EMPTY")){
					MsAdminRoleAuthority roleAuth=new MsAdminRoleAuthority(roleId,functionId);
					listRoleAuthority.add(roleAuth);
				}				
			}
			adminRoleAuthorityDao.batchSave(listRoleAuthority);
		}catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		
		/*
		try{
			List<String> addList = new ArrayList<String>();//要全部新增的functionId
			for(String f : functionIds){
				String functionOne = f;
				int numOne = 0;
				if(roleAuthorityList.size() != 0){
					for(MsAdminRoleAuthority bean : roleAuthorityList){
						String functionTwo = bean.getFunctionId();
						if(!functionOne.equals(functionTwo)){
							numOne++;
						}else{
							roleAuthorityList.remove(bean);
							break;
						}
						if(numOne == roleAuthorityList.size()&&!functionOne.equalsIgnoreCase("EMPTY")){
							addList.add(functionOne);
							break;
						}
					}
				}else{
					if(!functionOne.equalsIgnoreCase("EMPTY"))
					addList.add(functionOne);
				}
				
			}
			for(MsAdminRoleAuthority delBean:roleAuthorityList){
				System.out.println("functionId:"+delBean.getFunctionId()+"; roleId:"+delBean.getRoleId());
				String select = "from MsFunctionRoleOption where functionId='" + delBean.getFunctionId() + "'" + " and roleId='"+delBean.getRoleId()+"'";
				List<MsFunctionRoleOption> deBeanList = msFunctionRoleOptionDao.queryForList(select, null);
				msFunctionRoleOptionDao.deleteAll(deBeanList);
			}
			adminRoleAuthorityDao.deleteAll(roleAuthorityList);
			for(String functionId:addList){
				MsAdminRoleAuthority addBean = new MsAdminRoleAuthority();
				addBean.setFunctionId(functionId);
				addBean.setRoleId(roleId);
				System.out.println("functionId:"+functionId+"; roleId:"+roleId);
				adminRoleAuthorityDao.saveOrUpdate(addBean);
			}
		}catch (Exception e) {
			e.printStackTrace();
			throw e;
		}*/
		
	}

	@Override
	@Transactional(readOnly=true)
	public List<MsAdminFunction> findFunctionListByUserId(String userId) throws Exception {
		List<MsAdminFunction> resultList = null;	
		try {
			resultList = functionDao.findFunctionListByUserId(userId);
		} catch (Exception e) {
			throw e;
		}
		return resultList;
	}
	
}
